import os
import shutil
import sys

import facade
import parsel
from vip.id_encode import GetLngid
from xjlibrary.mdatetime.mtime import getTodayDate
from xjlibrary.mdatetime.mtime2 import MDateTimeUtils
from xjlibrary.our_file_dir import BaseDir
from xjlibrary.tools.BaseString import BaseString

curPath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curPath, -2)
sPath = BaseDir.get_new_path(TopPath, "download", "sublibbook", "download", "books")
db3dir = BaseDir.get_new_path(TopPath, "download", "sublibbook", "download", "db3")
BaseDir.create_dir(db3dir)
tempPath = BaseDir.get_new_path(curPath, "template")


class ParaBooks(object):

    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(BaseDir.get_new_path(curPath, "db.ini"), "db", self.logger)
        self.rawid = ''
        self.info = ''
        self.templatedb3 = BaseDir.get_new_path(tempPath, "zt_template.db3")
        self.new_db3_path = self.copyTempDB3(self.templatedb3, db3dir)
        self.db3_zt = facade.Sqlite3Utiles(logger=self.logger).Sqlite3DBConnectFromFilePath(
            self.new_db3_path, encoding="utf-8")
        self.Listpara = []

    def select(self):
        count = 0
        for file in BaseDir.get_dir_all_files(sPath):
            self.rawid = BaseDir.get_filename_not_extsep(file)
            html = BaseDir.single_read_file(file)
            self.para(html)
            self.create_para()
            count = count + 1
            print(count)
        self.insert_db3()

    def copyTempDB3(self, temp_path, copy_out):
        """
        拷贝创建新的db3文件
        :param temp_path: 模板db3文件路径
        :param copy_out: 新的db3输出路径
        :return: 新db3路径
        """
        today_str = str(getTodayDate())
        if not os.path.isfile(temp_path) or not os.path.isdir(copy_out):
            raise FileNotFoundError
        new_db3_name = 'zt_mirrorswjtucbsbook_' + today_str + '.db3'
        new_db3_path = os.path.join(copy_out, new_db3_name)
        shutil.copyfile(temp_path, new_db3_path)
        return new_db3_path

    def para(self, html):
        select = parsel.Selector(text=html)
        subject_list = select.xpath('/html/body/div[4]/div[1]/div/div//text()').getall()
        subject_list_clear = []
        for text in subject_list:
            text = text.strip()
            if text.find("您所在的位置") > -1:
                continue
            if text.find("〉") > -1:
                continue
            if text.find("：") > -1:
                continue
            if text:
                subject_list_clear.append(text)
        subject_path = ""
        for text in subject_list_clear:
            subject_path = subject_path + ";" + text
        title = select.xpath('//*[@id="bookDetailTitle"]/text()').get()
        legal_status = select.xpath('//*[@id="bookUnit"]/text()').get()
        identifier_standard = select.xpath(
            './/div[@class="book-Info"]/div[@class="row"]/div[2]/div[1]/div[1]/span/@title').get()
        name = select.xpath('.//div[@class="book-Info"]/div[@class="row"]/div[2]/div[1]/div[2]/span/@title').get()
        text_list = select.xpath(
            './/div[@class="book-Info"]/div[@class="row"]/div[2]/div[1]/div[@class="col-md-4"]')
        provider_subject = ""
        pub_date = ""
        date_impl = ""
        date_delete = ""
        old_id = ""
        new_id = ""
        for div in text_list:
            text = div.xpath(".//text()").get()
            if text.find("资源类型") > -1:
                provider_subject = text.replace("资源类型：", "").strip()
            elif text.find("发布日期") > -1:
                pub_date = text.replace("发布日期：", "").strip()
                pub_date = pub_date.replace("-", "")
            elif text.find("实施日期") > -1:
                date_impl = text.replace("实施日期：", "").strip()
                date_impl = date_impl.replace("-", "")
            elif text.find("废止日期") > -1:
                date_delete = text.replace("废止日期：", "").strip()
                date_delete = date_delete.replace("-", "")
            elif text.find("被代替标准号") > -1:
                old_id = div.xpath(".//a/text()").get()
            elif text.find("代替标准号") > -1:
                new_id = div.xpath(".//a/text()").get()
            else:
                if text in ["编号：", "名称："]:
                    continue
                print(text)
                print("出现其他字段")
                sys.exit(-1)

        creator_institution = select.xpath(
            './/div[@class="book-Info"]/div[@class="row"]/div[2]/div[1]/div[@class="col-md-12"]/text()').get()
        creator_institution = creator_institution.replace("主编单位：", "").strip()
        abstract = select.xpath('.//div[@class="info-carousel m-t-md"]/div[@class="bd"]/div[1]/text()').get()
        description = abstract.strip()
        description_unit_list = select.xpath(
            './/div[@class="info-carousel m-t-md"]/div[@class="bd"]/div[2]/div[1]/div[@class="col-md-9 col-sm-9 col-sx-9 text-left"]/text()').getall()
        description_unit = ""
        for text in description_unit_list:
            description_unit = description_unit + "\n" + text

        self.info = (
            subject_path, title, legal_status, identifier_standard, name, provider_subject, pub_date, date_impl,
            date_delete, old_id, new_id,
            creator_institution, description,
            description_unit)

    def create_para(self):
        sub_db_id = '00178'
        product = 'TS'
        sub_db = 'SWJTU'
        provider_zt = 'mirrorswjtucbsbook'
        provider = 'CBS'
        provider = provider_zt
        rawid = self.rawid
        lngid = GetLngid(sub_db_id, rawid)
        type_ = "1"
        medium = "2"
        country = "CN"
        language = "ZH"

        url = "http://202.115.72.61:9099/book/detail/show?SiteID=1&bookID={}".format(
            rawid)
        provider_url = provider_zt + "@" + url
        provider_id = provider_zt + "@" + rawid
        publisher = "中国建筑标准设计研究院"
        (subject_path, title, legal_status, identifier_standard, name, provider_subject, pub_date, date_impl,
         date_delete, old_id, new_id,
         creator_institution, description,
         description_unit) = self.info

        subject_path = BaseString.cleanSemicolon(subject_path)
        date_created = pub_date
        if pub_date:
            date = pub_date[:4]
        else:
            date = "1900"
            date_created = "19000000"
        batch = MDateTimeUtils.get_today_date_strings() + "00"
        sql = "select coverstat from books where url='{}'".format(url)
        rows = self.mysqlutils.SelectFromDB(sql)
        cover = ""
        if rows[0][0] == 1:
            cover = "/smartlib/{}/{}.jpg".format(provider, rawid)

        self.Listpara.append((lngid, rawid, title, country, language, cover, provider, batch,
                              type_, medium, provider_url, provider_id, date, date_created, provider_subject,
                              description, publisher, description_unit, identifier_standard, creator_institution,date_impl))

    def insert_db3(self):
        sql = "insert or ignore into modify_title_info_zt (`lngid`,`rawid`,`title`," \
              "`country`,`language`,`cover`,`provider`,`batch`," \
              "`type`,`medium`,`provider_url`,`provider_id`,`date`," \
              "`date_created`,`provider_subject`,`description`,publisher," \
              "description_unit,identifier_standard,creator_institution,date_impl) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"

        self.db3_zt.ExeSqlliteMany(sql, self.Listpara)
        self.Listpara.clear()


if __name__ == "__main__":
    para = ParaBooks()
    para.select()
